<template>
<div class="psychologyqn">
  <basic-container v-if="!isCreate">
    <avue-crud :option="option"
      :table-loading="loading"
      :data="data"
      :page="page"
      ref="crud"
      v-model="form"
      :permission="permissionList"
      :row-style="rowStyle"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @on-load="onLoad"
    >
      <template slot="menuLeft">
        <!-- <el-popover
          placement="top"
          width="160"
          trigger="click">
          <el-select v-model="qnType" placeholder="请选择问卷类型" @change="handleCreateQn">
            <el-option v-for="x in qnTypeDic" :key="x.value"
            :label="x.label" :value="x.value"></el-option>
          </el-select> -->
          <el-button slot="reference" type="primary" size="small" icon="el-icon-plus" @click="handleCreateQn">创建问卷</el-button>
          <el-button size="small" :loading="batchGLoading" @click="handleBatchGenerate">批量生成数据</el-button>
        <!-- </el-popover> -->
      </template>
      <template slot-scope="scope" slot="menu">
        <el-button type="text" size="small" icon="el-icon-view" @click="handleSeePreview(scope.row)">查看</el-button>
        <el-dropdown style="margin-left: 10px" type="text" size="mini">
          <el-button type="text" size="mini">
            更多<i class="el-icon-arrow-down el-icon--right"></i>
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <template v-if="scope.row.status == 2">
              <el-dropdown-item><el-button type="text" size="small" icon="el-icon-edit" @click="handleEdit(scope.row)">编辑</el-button></el-dropdown-item>
              <el-dropdown-item><el-button type="text" size="small" icon="el-icon-top" @click="handlePublish(scope.row)">发布</el-button></el-dropdown-item>
            </template>
            <template v-else-if="scope.row.status == 1">
              <el-dropdown-item><el-button type="text" size="small"  @click="handleRecall(scope.row)" >撤回</el-button></el-dropdown-item>
              <el-dropdown-item><el-button type="text" size="small" @click="handleViewStatistics(scope.row)">查看统计</el-button></el-dropdown-item>
              <el-dropdown-item><el-button type="text" size="small" @click="handleCopyOrAnswer(scope.row)">二维码和链接</el-button></el-dropdown-item>
            </template>
            <el-dropdown-item><el-button type="text" size="small" icon="el-icon-document-copy" @click="handleCopy(scope.row)">复制</el-button></el-dropdown-item>
            <el-dropdown-item><el-button type="text" size="small" @click="handleGenerate(scope.row)">生成数据</el-button></el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </template>
      <template slot="qrCode" slot-scope="scope">
        <el-popover
          placement="top-start"
          width="200"
          trigger="hover"
        >
          <template slot="reference">
            <el-button v-show="scope.row.status == 1" type="text">查看二维码</el-button>
          </template>
          <el-image
            :src="scope.row.qrCode"
            fit="cover"
            style="width: 100%; height: 100%;"/>
        </el-popover>
      </template>
    </avue-crud>
    <AnswerPage ref="answerpage" :dialogVisible="answerDialog" @close="handleCloseAnswer"/>
    <!-- <ViewStatistics v-if="viewStatDialog" ref="viewstat" :dialogVisible="viewStatDialog" :rowId="rowId" @close="handleCloseViewStat"/> -->
  </basic-container>
  <div class="createPsyTemp" v-else>
    <div v-if="beforeCreate" style="padding: 0 10px;">
      <div class="create-qn">
        <header><el-button type="warning" icon="el-icon-back" size="small" @click.stop="isCreate = false"></el-button>创建问卷</header>
        <div class="create-qn-content">
          <h4>从空白创建</h4>
          <el-input v-model="createTitle" placeholder="请输入标题" @input="handleChange" @blur="handleChange"></el-input>
          <label v-show="isSubmit">请输入标题</label>
          <el-button type="primary" @click="submitQnTitle">立&nbsp;即&nbsp;创&nbsp;建</el-button>
        </div>
      </div>
      <div class="searchAndList">
        <div class="searchInp">
          <label for="searchinp">搜索：</label>
          <el-input id="searchinp" placeholder="请输入内容" v-model="searchTemp" class="input-with-select">
            <el-button slot="append" icon="el-icon-search" @click="getPsyTemp"></el-button>
          </el-input>
          <div style="background-color: #fff; text-align:center; margin-left: 15px;">
            <el-pagination
              @size-change="handleSizeChangeTemp"
              @current-change="handleCurrentChangeTemp"
              :current-page.sync="currentPageTemp"
              :page-sizes="[15,30,45,60,75,90,100]"
              :page-size="tempSize"
              layout="sizes, prev, pager, next, total"
              :total="tempTotal">
            </el-pagination>
          </div>
        </div>
        <div class="tempList">
          <div class="temps" v-for="(item,ind) in tempList" :key="ind" @click="handleTempCreate(item, ind)">
            <div class="tempTitle">{{item.title}}</div>
            <div class="tempFoot">
              <div class="left">共 {{ item.count }} 题，使用 {{ item.useNumber }} 次</div>
              <div>去使用</div>
            </div>
          </div>
        </div>

      </div>
    </div>
    <div class="editSetqn" v-else>
      <el-tabs v-model="activeName" v-loading="seeandeditLoading" :before-leave="beforeLeaveTab" @tab-click="tabClick">

        <el-tab-pane label="设置问卷" name="setqn">
          <div style="width: 50%; margin: 0 auto;">
            <el-form :model="qnForm" :rules="rules" ref="qnForm" :disabled="visibleStatus == 'view'" label-width="100px" class="qnForm">
              <el-form-item label="开始时间" prop="startTime">
                  <el-date-picker type="datetime" value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择日期" v-model="qnForm.startTime" style="width: 100%;"></el-date-picker>
              </el-form-item>
              <el-form-item label="结束时间" prop="endTime">
                  <el-date-picker type="datetime" value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择日期" v-model="qnForm.endTime" style="width: 100%;"></el-date-picker>
              </el-form-item>
              <el-form-item label="是否公开" prop="isPublic">
                  <el-radio-group v-model="qnForm.isPublic">
                    <el-radio :label="1">是</el-radio>
                    <el-radio :label="0">否</el-radio>
                  </el-radio-group>
              </el-form-item>
              <el-form-item v-if="qnForm.isPublic == 0" label="调研学校" prop="school">
                <el-select
                  v-model="qnForm.school"
                  style="width: 100%;"
                  ref="selectSchool"
                >
                  <el-option>
                    <div style="padding: 10px;"><el-input @click.native.stop placeholder="输入关键字进行过滤" v-model="filterTextSchool"></el-input></div>
                    <el-tree
                      class="filter-tree"
                      :data="treeSchoolData"
                      :props="schoolProps"
                      :filter-node-method="filterNodeSchool"
                      node-key="id"
                      @node-click="handleSchoolClick"
                      ref="treeSchool">
                    </el-tree>
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item v-if="qnForm.isPublic == 0" label="调研班级" prop="classGrade">
                <el-select
                  v-model="qnForm.classGrade"
                  ref="select"
                  style="width: 100%;"
                >
                  <el-option>
                    <div style="padding: 10px;"><el-input @click.native.stop placeholder="输入关键字进行过滤" v-model="filterText"></el-input></div>
                    <el-tree
                      class="filter-tree"
                      :data="treeData"
                      :props="defaultProps"
                      :filter-node-method="filterNode"
                      show-checkbox
                      node-key="id"
                      @check-change="handleCheckChange"
                      ref="tree">
                    </el-tree>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-form>
            <div style="width: 100%; display: flex; justify-content: center;">
              <el-button @click="handleCancle">取消</el-button>
              <el-button type="primary" v-show="visibleStatus != 'view'" :loading="saveLoading" @click="submitSetqnForm(2)">保存</el-button>
              <el-button type="primary" v-show="visibleStatus != 'view'" :loading="publishLoading" @click="publishSetqnForm(1)">发布</el-button>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="编辑选项" name="editopt">
          <TemplateEdit v-if="!beforeCreate" ref="tempEdit" :isShowViewSaveBtn="isShowViewSaveBtn" :right="50" :top="160" @on-save="handleTempEditSave" @on-editsave="handleEveryTopicSave" @on-preview="handleTempPreview"/>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</div>
</template>

<script>
import { getSchoolTree, getSurveyRange, getList, getDetail, getTemplate, getTemplateDetail, addOrUpdatePsyTemp, publishOrCancelPsyTemp, copyPsyTemp, deletePsyTemp, generateData } from "@/api/platform/psychologyQuestionnaire";
import { mapGetters } from "vuex";
import TemplateEdit from '../templateManage/index.vue'
import ViewStatistics from "./viewStatistics.vue";
import { formatDate } from '@/util/util'
import AnswerPage from './answerPage.vue'
import { getNewSort } from '../templateManage/utils'

export default {
  components: { TemplateEdit, ViewStatistics, AnswerPage },
  data() {
    return {
      form: {},
      loading: true,
      selectionList: [],
      query: {},
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      option: {
        searchShow: true,
        searchMenuSpan: 6,
        tree: false,
        tip: false,
        border: true,
        index: true,
        selection: true,
        addBtn: false,
        menuWidth: 170,
        editBtn: false,
        viewBtn: false,
        column: [
          {
            label: "学校",
            prop: "schoolId",
            search: true,
            type: 'tree',
            rules: [
              {
                required: true,
                message: "请选择学校",
                trigger: "blur"
              }
            ],
            props: {
              label: "xxName",
              value: "id"
            },
            dicData: [],
          },
          {
            label: "问卷ID",
            prop: "id",
            type: 'select',
            width: 70
          },
          {
            label: "问卷标题",
            prop: "title",
            search: true,
            type: 'input'
          },
          {
            label: "开始时间",
            prop: "startTime",
            search: true,
            type: 'datetime',
            format: 'yyyy-MM-dd HH:mm', // 日期格式
            valueFormat: 'yyyy-MM-dd HH:mm:ss'
          },
          {
            label: "结束时间",
            prop: "endTime",
            search: true,
            type: 'datetime',
            format: 'yyyy-MM-dd HH:mm', // 日期格式
            valueFormat: 'yyyy-MM-dd HH:mm:ss'
          },
          {
            label: "创建时间",
            prop: "createTime",
            search: true,
            type: 'datetime',
            format: 'yyyy-MM-dd HH:mm', // 日期格式
            valueFormat: 'yyyy-MM-dd HH:mm:ss'
          },
          {
            label: "状态",
            prop: "status",
            search: true,
            type: 'select',
            dicData: [
              {
                label: '发布',
                value: 1
              },
              {
                label: '未发布',
                value: 2
              },
            ]
          },
          {
            label: '公众号二维码',
            prop: 'qrCode',
          }
        ]
      },
      data: [],
      qnTypeDic: [],
      qnType: '',
      visibleStatus: 'add',//add edit view
      // 空白创建
      isCreate: false,
      isSubmit: false,
      createTitle: '',
      searchTemp: '',
      tempList: [
        /* {
          title: '化学期中考试',
          total: 12,
        },
        {
          title: '化学期中考试',
          total: 12,
        },
        {
          title: '化学期中考试',
          total: 12,
        },{
          title: '化学期中考试',
          total: 12,
        },
        {
          title: '生物期中考试',
          total: 12,
        },
        {
          title: '数学期中考试',
          total: 12,
        },
        {
          title: '思想品德期中考试',
          total: 12,
        },
        {
          title: '化学期中考试',
          total: 12,
        },
        {
          title: '化学期中考试',
          total: 12,
        },
        {
          title: '化学期中考试',
          total: 12,
        },
        {
          title: '化学期中考试',
          total: 12,
        },
        {
          title: '化学期中考试',
          total: 12,
        },
        {
          title: '化学期中考试',
          total: 12,
        },
        {
          title: '化学期中考试',
          total: 12,
        },
        {
          title: '化学期中考试',
          total: 12,
        },


        {
          title: '化学期中考试',
          total: 12,
        }, */
      ],

      // 是否创建前
      beforeCreate: true,
      activeName: 'setqn',
      qnForm: {
        startTime: '',
        endTime: '',
        classGrade: '',
        school: '',
        scopeInfoList: [],
        isPublic: 1
      },
      // 选中的学校id
      selectSchoolID: '',
      rules: {
        startTime: [
          { required: true, message: '请选择开始时间', trigger: 'change' }
        ],
        endTime: [
          { required: true, message: '请选择结束时间', trigger: 'change' }
        ],
        school: [
          { required: true, message: '请选择学校', trigger: 'change' }
        ],
        classGrade:[
          { required: true, message: '请选择班级', trigger: 'change' }
        ],

      },
      filterText: '',
      filterTextSchool: '',
      treeData: [{
          id: 1,
          label: '一级 1',
          children: [{
            id: 4,
            label: '二级 1-1',
            children: [{
              id: 9,
              label: '三级 1-1-1'
            }, {
              id: 10,
              label: '三级 1-1-2'
            }]
          }]
        }, {
          id: 2,
          label: '一级 2',
          children: [{
            id: 5,
            label: '二级 2-1'
          }, {
            id: 6,
            label: '二级 2-2'
          }]
        }, {
          id: 3,
          label: '一级 3',
          children: [{
            id: 7,
            label: '二级 3-1'
          }, {
            id: 8,
            label: '二级 3-2'
          }]
      }],
      defaultProps: {
        children: 'children',
        label: 'title'
      },
      treeSchoolData: [],
      schoolProps: {
        label: 'xxName',
        children: 'children'
      },
      editSaveTemp: {},// 暂存模板保存下来的内容
      completeEdit: false,// 是否点击完成编辑按钮
      everyId: '0',//每次保存获得id
      viewStatDialog: false,// 查看统计
      rowId: '0',
      isShowViewSaveBtn: true,
      answerDialog: false,
      // 下边俩供查看编辑时问卷数据存储
      otherPropsObject: {},
      questDtosArray: [],
      // 查看编辑的loading
      seeandeditLoading: false,
      templateCreate: false,
      qnnLoading: true,

      // 模板创建分页
      currentPageTemp: 1,
      tempSize: 15,
      tempTotal: 0,
      saveLoading: false,
      publishLoading: false,
      // 模板id
      templateId: 0,
      batchGLoading: false
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    },
    filterTextSchool(val) {
      this.$refs.treeSchool.filter(val);
    }
  },

  computed: {
    ...mapGetters(["userInfo", "permission"]),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.menu_add, false),
        viewBtn: this.vaildData(this.permission.menu_view, false),
        // delBtn: this.vaildData(this.permission.menu_delete, false),
        editBtn: this.vaildData(this.permission.menu_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    }
  },
  methods: {
    // 控制原生按钮显隐
    rowStyle(col) {
      if (col.row.status == 2) {
        this.option.delBtn = true
      } else if (col.row.status == 1) {
        this.option.delBtn = false
      }
    },
    getTree() {
      getSchoolTree().then(res => {
        const column = this.findObject(this.option.column, "schoolId");
        column.dicData = res.data.data;
        this.treeSchoolData = res.data.data;
      })
    },
    handleCreateQn() {
      this.visibleStatus = 'add'
      this.isCreate = true
      this.getPsyTemp()
    },
    // seeview
    handleSeePreview(row) {
      this.isShowViewSaveBtn = false
      this.visibleStatus = 'view'
      this.isCreate = true
      this.beforeCreate = false
      this.everyId = row.id
      this.seeandeditLoading = true
      getDetail({ id: row.id }).then(res => {
        const d = res.data && res.data.data
        const { questDtos, ...otherProps } = d
        this.otherPropsObject = { ...otherProps }
        let _questDtosArray = Array.isArray(questDtos) ? questDtos : []
        this.questDtosArray = _questDtosArray.map(item => {
          delete item.isHover
          return item
        })
        this.$nextTick(() => {
          // 设置问卷回显
          setTimeout(() => {
            this.$refs.treeSchool && this.$refs.treeSchool.setCurrentKey(row.schoolId)
          }, 1000);
          this.selectSchoolID = row.schoolId
          this.getScope().then(() => {
            this.$refs.tree.setCheckedKeys(this.otherPropsObject.scopeInfoList, true)
          })
        })
        this.qnForm.startTime = row.startTime
        this.qnForm.endTime = row.endTime
        this.qnForm.school = row.$schoolId
        this.qnForm.isPublic = this.otherPropsObject.isPublic
      }).finally(() => {
        this.seeandeditLoading = false
      })
    },
    handleEdit(row) {
      this.visibleStatus = 'edit'
      this.isCreate = true
      this.beforeCreate = false
      this.everyId = row.id
      this.seeandeditLoading = true
      getDetail({ id: row.id }).then(res => {
        const d = res.data && res.data.data
        const { questDtos, ...otherProps } = d
        this.otherPropsObject = { ...otherProps }
        this.questDtosArray = Array.isArray(questDtos) ? questDtos : []
        this.$nextTick(() => {
          // this.$refs.tempEdit.questionnaire = otherPropsObject
          // this.$refs.tempEdit.questionnaireList = questDtosArray

          // 设置问卷回显
          setTimeout(() => {
            this.$refs.treeSchool && this.$refs.treeSchool.setCurrentKey(row.schoolId)
          }, 1000);
          this.selectSchoolID = row.schoolId
          this.getScope().then(() => {
            this.$refs.tree.setCheckedKeys(this.otherPropsObject.scopeInfoList, true)
          })
        })
        this.qnForm.startTime = row.startTime
        this.qnForm.endTime = row.endTime
        this.qnForm.school = row.$schoolId
        this.qnForm.isPublic = this.otherPropsObject.isPublic

        // 编辑不查看问卷模板直接保存保证拿到模板信息
        this.editSaveTemp = {
          ...otherProps,
          questDtos
        }
      }).finally(() => {
        this.seeandeditLoading = false
      })
    },
    // 选项卡点击切换
    tabClick(src) {
      if (src.name == "editopt" && !this.seeandeditLoading) {
        if(this.visibleStatus == 'add' && !this.templateCreate) return
        if (this.otherPropsObject.source_type == '1') {
          this.isShowViewSaveBtn = false
          this.questDtosArray = this.questDtosArray.map(item => {
            delete item.isHover
            return item
          })
        }
        this.$nextTick(() => {
          this.$refs.tempEdit.questionnaire = this.otherPropsObject
          this.$refs.tempEdit.questionnaireList = this.questDtosArray
        })
      }
    },
    handleCopy(row) {
      copyPsyTemp({ id: row.id }).then(res => {
        if (res.data.code === 200) {
          this.$message.success('复制成功')
          this.onLoad(this.page, {})
        }
      })
    },
    handlePublish(row) {
      publishOrCancelPsyTemp({id: row.id}).then(res=>{
        this.$message({type: 'success', message: res.data.msg || '操作成功'})
        this.onLoad(this.page, {})
      })
    },
    handleRecall(row) {
      publishOrCancelPsyTemp({id: row.id}).then(res=>{
        this.$message({type: 'success', message: res.data.msg || '操作成功'})
        this.onLoad(this.page, {})
      })
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return deletePsyTemp({id: row.id});
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
        this.loading = false;
        this.page.total = res.data.data.total;
        this.data = res.data.data.records;
        this.getTree()
      })
    },
    handleChange() {
      if (this.createTitle != '') this.isSubmit = false
    },
    submitQnTitle() {
      if (this.createTitle == '') {
        this.isSubmit = true
        return
      }
      this.beforeCreate = false
      this.activeName = 'editopt'
      this.templateCreate = false
      this.$nextTick(() => {
        this.$refs.tempEdit.questionnaire.title = this.createTitle
        this.$refs.tempEdit.questionnaire.typeId = '1689888744139960327'
      })
    },
    handleSizeChangeTemp(val){
      this.tempSize = val
      this.getPsyTemp()
    },
    handleCurrentChangeTemp(val){
      this.currentPageTemp = val
      this.getPsyTemp()
    },
    // 获得心里模板
    getPsyTemp() {
      getTemplate({
        title: this.searchTemp,
        size: this.tempSize,
        current: this.currentPageTemp
      }).then(res => {
        const d = res.data && res.data.data
        this.tempList = d.records
        this.tempTotal = d.total
      })
    },
    // 模板编辑保存
    handleTempEditSave(val) {
      this.activeName = 'setqn'
      this.editSaveTemp = val
      this.completeEdit = true
    },
    // 模板每题目保存
    handleEveryTopicSave(val) {
      if (this.visibleStatus == 'add') {
        const { year, month, day, hours, minutes, seconds } = formatDate()
        const endTime = `${year}-${month}-${+day + 1} ${hours}:${minutes}:${seconds}`
        const startTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
        addOrUpdatePsyTemp({
          ...val, id: this.everyId, status: 2,
          scopeInfoList: this.qnForm.scopeInfoList,
          startTime: this.qnForm.startTime ? this.qnForm.startTime : startTime,
          endTime: this.qnForm.endTime ? this.qnForm.endTime : endTime,
          schoolId: this.selectSchoolID || 0,
          sourceType: 0,
          sourceId: this.templateCreate ? this.templateId : 0
        }).then(res => {
          this.everyId = res.data.data
        })
      }
    },
    // 预览
    handleTempPreview(val) {
      if (this.visibleStatus == 'edit' || this.everyId != '0') {
        this.$router.push({ path: '/templateManage/previewPage', query: { id: this.everyId, type: 2 } })
      } else {
        const { year, month, day, hours, minutes, seconds } = formatDate()
        const endTime = `${year}-${month}-${+day + 1} ${hours}:${minutes}:${seconds}`
        const startTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
        const d = {
          ...val,
          id: this.everyId,
          status: 2,

          // 设置部分
          scopeInfoList: this.qnForm.scopeInfoList,
          startTime: this.qnForm.startTime ? this.qnForm.startTime : startTime,
          endTime: this.qnForm.endTime ? this.qnForm.endTime : endTime,
          schoolId: this.selectSchoolID || 0,
          sourceType: this.templateCreate ? 1 : 0,
          sourceId: this.templateCreate ? this.templateId : 0
        }
        addOrUpdatePsyTemp(d).then(res => {
          this.everyId = res.data.data
          this.$router.push({ path: '/templateManage/previewPage', query: { id: this.everyId, type: 2 } })
        })
      }
    },
    // 从模板创建
    handleTempCreate(item) {
      this.beforeCreate = false
      // this.activeName = 'editopt'
      this.isShowViewSaveBtn = false
      this.templateCreate = true
      this.templateId = item.id
      this.qnnLoading = true
      getTemplateDetail({ id: item.id }).then(res => {
        const d = res.data && res.data.data
        const { questDtos, ...otherProps } = d
        this.otherPropsObject = { ...otherProps, id: '0' }
        this.questDtosArray = (Array.isArray(questDtos) ? questDtos : []).map(item => {
          delete item.isHover
          return item
        })
        this.editSaveTemp = {
          ...this.otherPropsObject,
          questDtos: getNewSort(this.questDtosArray)
        }
        this.qnnLoading = false
        this.$nextTick(() => {
          this.$refs.tempEdit.questionnaire = this.otherPropsObject
          this.$refs.tempEdit.questionnaireList = this.questDtosArray
        })
      })
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    filterNodeSchool(val, data) {
      if (!val) return true;
      return data.xxName.indexOf(val) !== -1;
    },
    // 获取班级信息调查范围
    getScope() {
      return getSurveyRange({ schoolId: this.selectSchoolID }).then(res => {
        this.treeData = res.data.data
      })
    },
    handleSchoolClick(obj) {
      this.selectSchoolID = obj.id
      this.qnForm.school = obj.xxName
      this.$nextTick(() => {
        this.$refs.selectSchool.blur()
      })
      this.getScope()
    },
    handleCheckChange() {
      const nodes = this.$refs.tree.getCheckedNodes()
      console.log('%c December0v0 ','background-image:linear-gradient(135deg,#F1F2B5,#18545A);color:#fff;',
        nodes)
      const lastNode = nodes.filter(node => node.hasChildren)
      this.qnForm.scopeInfoList = lastNode.map(n => n.id)
      this.qnForm.classGrade = lastNode.map(n => {
        let name = []
        if(nodes.length == lastNode.length) return n.title
        nodes.forEach(parent => {
          if (n.parentId === parent.id) {
            name.push(`${parent.title}${n.title}`)
            return
          }
        })
        return name
      }).join(',')
    },
    savePubOrSub(status) {
      this.$refs.qnForm.validate(vali => {
        if (vali) {
          console.log('%c December0v0 ','background-image:linear-gradient(135deg,#fff799,#18545A);color:#fff;',
            'chenggong ', this.qnForm, this.editSaveTemp)
          const data = {
            ...this.editSaveTemp,
            scopeInfoList: this.qnForm.scopeInfoList,
            startTime: this.qnForm.startTime,
            endTime: this.qnForm.endTime,
            isPublic: this.qnForm.isPublic,
            schoolId: this.selectSchoolID || 0,
            status,
            id: this.everyId,
            sourceType: this.templateCreate ? 1 : 0,
            sourceId: this.templateCreate ? this.templateId : 0
          }
          addOrUpdatePsyTemp(data).then(res => {
            if (res.data.code == 200) {
              this.$message({
                type: 'success',
                message: res.data.msg || '保存成功'
              })
            } else {
              this.$message({
                type: 'error',
                message: res.data.msg || '保存失败'
              })
            }
            this.handleCancle()
          }).finally(() => {
            setTimeout(() => {
              this.saveLoading = false
              this.publishLoading = false
            }, 500);
          })
        } else {
          this.saveLoading = false
          this.publishLoading = false
        }
      })
    },
    // 切换tabs
    beforeLeaveTab(active) {
      if(this.completeEdit || this.visibleStatus == 'view') return true
      if (active == 'setqn') {
        // this.$message.info('请先完成编辑保存 ！')
        this.$nextTick(() => {
          this.editSaveTemp = this.$refs.tempEdit.offerQnData()
        })
        return true
      }
    },
    // 提交
    submitSetqnForm(status) {
      this.saveLoading = true
      this.savePubOrSub(status)
    },
    // 发布
    publishSetqnForm(status) {
      this.$confirm('确定发布?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.publishLoading = true
        this.savePubOrSub(status)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        });
      });
    },
    handleCancle() {
      this.isCreate = false
      this.beforeCreate = true
      this.activeName = 'setqn'
      this.qnForm = {
        startTime: '',
        endTime: '',
        classGrade: '',
        school: '',
        scopeInfoList: [],
        isPublic: 1
      }
      this.selectSchoolID = ''
      this.createTitle = ''
      this.completeEdit = false
      this.everyId = '0'
      this.isShowViewSaveBtn = true
      this.otherPropsObject = {}
      this.questDtosArray = []
      this.templateId = 0
    },

    // 查看统计
    handleViewStatistics(row) {
      // this.viewStatDialog = true
      this.rowId = row.id
      // this.$nextTick(() => {
      //   this.$refs.viewstat.schoolList = this.treeSchoolData
      // })
      this.$router.push({path:'/platform/viewStatistics', query:{id:row.id}})
    },
    // 去答题
    handleCopyOrAnswer(row) {
      this.$nextTick(() => {
        this.$refs.answerpage.getFromParentData(row)
      })
      this.answerDialog = true
    },
    handleCloseAnswer(val) {
      this.answerDialog = val
    },
    // handleCloseViewStat(val) {
    //   this.viewStatDialog = val
    // }
    handleGenerate(row) {
      this.$confirm("此操作会清除之前问卷已经生成的数据，是否要重新生成?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          generateData({ ids: row.id }).then(res => {
            if (res.data.code == 200) {
              this.$message.success(res.data.msg || '生成成功')
            }
          })
        })
    },
    handleBatchGenerate() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("此操作会清除之前问卷已经生成的数据，是否要重新生成?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.batchGLoading = true
          generateData({ ids: this.ids }).then(res => {
            if (res.data.code == 200) {
              this.$message.success(res.data.msg || '批量生成成功')
            }
          }).finally(() => {
            this.batchGLoading = false
          })
        })
    }
  }
};
</script>

<style scope lang="scss">
.psychologyqn{
  .createPsyTemp{
    width: 100%;
    .create-qn{
      width: 60%;
      >header{
        font-size: 20px;
        font-weight: bold;
        margin-bottom: 20px;
        display: flex;
        align-content: center;
      }
      .create-qn-content{
        background-color: #fff;
        box-sizing: border-box;
        padding: 20px 30px;
        border-radius: 10px;
        display: flex;
        flex-direction: column;
        align-items: center;
        >h4{
          text-align: center;
        }
        >.el-button{
          margin: 20px;
        }
        label{
          display: inline-block;
          width: 100%;
          color: red;
          font-size: 14px;
        }
      }
    }

    .searchInp{
      width: 100%;
      margin: 20px 0;
      display: flex;
      align-items: center;
      >label{
        display: inline-block;
        width: 100px;
        font-size: 20px;
      }
    }
    .tempList{
      width: 100%;
      height: 300px;
      overflow-y: scroll;

      .temps{
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        float: left;
        width: 238px;
        height: 80px;
        background-color: #fff;
        box-sizing: border-box;
        padding: 10px 12px;
        margin-right: 12px;
        margin-bottom: 12px;
        .tempTitle{
          color: #4d4d4d;
          font-size: 14px;
        }
        .tempFoot{
          font-size: 12px;
          color: #a9a9a9;
          display: flex;
          justify-content: space-between;
        }
        &:hover{
          cursor: pointer;
          background-color: #e8e5e5;
        }
      }
    }

    .editSetqn{
      width: 100%;
      // height: 100vh;
      background-color: #fff;
      box-sizing: border-box;
      padding: 0 20px;

      .qnForm{

        .el-select{
          width: 100%;
        }
      }

    }
  }
}
</style>
